package com.future.hedongjun.common;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.future.baselib.utils.UserInfoSharePreference;
import com.future.hedongjun.mine.MsgPushPreference;
import com.future.hedongjun.mine.bean.UserInfo;
import com.future.hedongjun.mine.ui.LoginActivity;
import com.google.gson.Gson;
import com.kingsoft.media.httpcache.KSYProxyService;
import com.mob.MobSDK;

import cn.jpush.android.api.JPushInterface;

/**
 * @author jniu
 * @Email niuxiaoqi@hztianque.com
 * @time 2018/11/10
 */
public class MyApp extends Application {

    private static MyApp instance;
    //    private String userToken = "";
//    private String userToken = "7943492520c9a1ba7a4537d3113066d3";
    private UserInfo userInfo;
    private static KSYProxyService proxyService = null;
    private static Context cc;
    private static MyApp app = null;
    public static boolean isFlag = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        MobSDK.init(this);
        JPushInterface.init(this);
        if (MsgPushPreference.getInstance(this).canPush()) {
            JPushInterface.resumePush(this);
        } else {
            JPushInterface.stopPush(this);
        }
    }

    public static MyApp getInstance() {
        return instance;
    }

    public UserInfo getUserInfo() {
        if (userInfo == null) {
            String infoStr = UserInfoSharePreference.getInstance(this).getUserInfo();
            if (!TextUtils.isEmpty(infoStr)) {
                userInfo = new Gson().fromJson(infoStr, UserInfo.class);
            }
        }
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        if (userInfo == null) {
            UserInfoSharePreference.getInstance(this).setUserInfo("");
            this.userInfo = null;
        } else {
            this.userInfo = userInfo;
            UserInfoSharePreference.getInstance(this).setUserInfo(new Gson().toJson(userInfo));
        }
    }

    public boolean hasLogin() {
        return getUserInfo() != null;
    }

    public String getUserToken() {
//        if (TextUtils.isEmpty(userToken)) {
//            userToken = UserInfoSharePreference.getInstance(this).getUserToken();
//            //JPushInterface.setAlias(this,0,MyApp.getInstance().getUserToken());
//        }
        return "";
    }


    public boolean checkLogin() {
        if (!hasLogin()) {
            startActivity(new Intent(this, LoginActivity.class));
            return false;
        }
        return true;
    }

    public static KSYProxyService getKSYProxy(Context context) {
        cc = context;
        if (app == null) {
            app = new MyApp();
        }
        return app.proxyService == null ? (app.proxyService = newKSYProxy()) : app.proxyService;
    }

    private static KSYProxyService newKSYProxy() {
        return new KSYProxyService(cc);
    }
}
